package com.starhub.monitor.service.impl;

import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.monitor.dao.AIChatLogMapper;
import com.starhub.monitor.dto.AIChatLogDto;
import com.starhub.monitor.entity.AIChatLog;
import com.starhub.monitor.service.IAIChatLogService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class AIChatLogServiceImpl implements IAIChatLogService {

    @Autowired
    private AIChatLogMapper aiChatLogMapper;

    @Override
    public Long logAIChat(AIChatLog log) {
        log.setId(IdGenerator.generateId());
        aiChatLogMapper.insert(log);
        return log.getId();
    }

    @Override
    public Long logSuccess(AIChatLogDto logDto) {
        long duration = ChronoUnit.MILLIS.between(logDto.getRequestTime(), logDto.getResponseTime());

        AIChatLog log = AIChatLog.builder()
                .userId(logDto.getUserId())
                .agentId(logDto.getAgentId())
                .modelName(logDto.getModelName())
                .sessionId(logDto.getSessionId())
                .messageId(logDto.getMessageId())
                .status(1)
                .requestTime(logDto.getRequestTime())
                .responseTime(logDto.getResponseTime())
                .duration(duration)
                .requestContent(logDto.getRequestContent())
                .responseContent(logDto.getResponseContent())
                .build();

        return logAIChat(log);
    }

    @Override
    public Long logFailure(AIChatLogDto logDto) {
        long duration = ChronoUnit.MILLIS.between(logDto.getRequestTime(), logDto.getResponseTime());

        AIChatLog log = AIChatLog.builder()
                .userId(logDto.getUserId())
                .agentId(logDto.getAgentId())
                .modelName(logDto.getModelName())
                .sessionId(logDto.getSessionId())
                .messageId(logDto.getMessageId())
                .status(0)
                .errorMessage(logDto.getErrorMessage())
                .requestTime(logDto.getRequestTime())
                .responseTime(logDto.getResponseTime())
                .duration(duration)
                .requestContent(logDto.getRequestContent())
                .build();

        return logAIChat(log);
    }
} 